package com.explorati.interview.interview.chapternine;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class NewInstanceTest {

	public static void main(String[] args) {
		try {
			Class clazz = Class.forName("com.explorati.interview.interview.chapternine.Student");
			// 使用不带参数的构造方法
			Student stu = (Student) clazz.newInstance();
			Field name = stu.getClass().getDeclaredField("name");
			name.setAccessible(true);
			name.set(stu, "zhangsan");
			System.out.println(stu);
			
			Class class1 = Student.class;
			Method method = class1.getDeclaredMethod("setName", String.class);
			method.setAccessible(true);
			Student stu1 = (Student) class1.newInstance();
			method.invoke(stu1, "lisi");
//			Field field1 = class1.getDeclaredField("name");
//			field1.setAccessible(true);
//			Student stu1 = (Student) class1.newInstance();
//			field1.set(stu1, "lisi");

			Class clazz1 = Student.class;
			Field name2 = clazz1.getDeclaredField("name");
			name2.setAccessible(true);
			Student stu2 = (Student) clazz1.newInstance();
			System.out.println(stu2);

			// 使用带参数的构造方法
			Constructor con = clazz1.getConstructor(String.class, int.class);
			Student stu3 = (Student) con.newInstance("wangwu", 10);
			System.out.println(stu3);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
